package org.hilo.boot.core.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.jretty.util.Const;
import org.springframework.util.StreamUtils;

/**
 * 
 * @author zollty
 * @since 2020年11月18日
 */
public class HiloHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private CachedServletInputStream cacheStream;
    
    public HiloHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (cacheStream != null) {
            cacheStream.reset(); // 复用
            return cacheStream;
        }
        return super.getInputStream();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        if (cacheStream != null) {
            cacheStream.reset(); // 复用
            return new BufferedReader(new InputStreamReader(cacheStream, getCharacterEncoding()));
        }
        return super.getReader();
    }
    
    @Override
    public String getCharacterEncoding() {
        String enc = super.getCharacterEncoding();
        return (enc != null ? enc : Const.UTF_8);
    }

    public ServletInputStream getBody() throws IOException {
        if (cacheStream != null) {
            cacheStream.reset(); // 复用
            return cacheStream;
        }
        cacheStream = new CachedServletInputStream(super.getInputStream());
        return cacheStream;
    }
    
    /**
     * Usage:
     * @see HttpServletRequestHelper#getBodyIfNecessary()
     */
    public String getBodyString() throws IOException {
        return StreamUtils.copyToString(getBody(), Charset.forName(getCharacterEncoding()));
    }

}
